# -*- coding: utf-8 -*-
"""
Created on Wed Sep  7 15:50:52 2022

@author: wulong
"""
'tag = 1 indicates this is first time of iteration'
'data comes from last time step'
'tag != 1 indicates this is not first time of iteration'
'data comes from last iterative step'

import numpy as np
from casadi import *
from Fast_1_formulate_Opt import *
from Obtain_results import *
from Transfer_fast import *

def F1_EMPC(initial_state, state_guess, state_bnds_lo, state_bnds_up,
            slow_state_bnds, fast_2_state_bnds, fast_3_state_bnds,
            slow_input_bnds, fast_2_input_bnds, fast_3_input_bnds,
            input_guess, input_bnds_lo, input_bnds_up,
            input_bin_bnds,
            distb_bnds,
            output_guess, output_bnds_lo, output_bnds_up,
            fast_state_setpnts, fast_input_setpnts,
            alpha, alpha_xf, alpha_uf, pred_horzn,
            pf, pmg, pse,
            tag, pred_horzn_fast_2, pred_horzn_fast_3, X_int_f2, X_int_f3, 
            i, del_Uc, past_Uc, past_Uz,
            alpha_ue, Uc_nb, It_d_Uc, Uc_it_sq,
            pre_d_Uc, pre_sq_Uc, pre_sq_Uz,
            pcm, ppn, rxi, rxi_as, yeb):
    
    f2_x_u = fast_x_u(pred_horzn, pred_horzn_fast_2,
                      fast_2_state_bnds, fast_2_input_bnds, tag, i)
    fast_2_state_bnds_new = f2_x_u[0]
    fast_2_input_bnds_new = f2_x_u[1]
    
    f3_x_u = fast_x_u(pred_horzn, pred_horzn_fast_3,
                      fast_3_state_bnds, fast_3_input_bnds, tag, i)
    fast_3_state_bnds_new = f3_x_u[0]
    fast_3_input_bnds_new = f3_x_u[1]
    
    f_opt = formulate_opt_f1(initial_state, state_guess, state_bnds_lo, state_bnds_up,
                             slow_state_bnds, fast_2_state_bnds_new, fast_3_state_bnds_new,
                             slow_input_bnds, fast_2_input_bnds_new, fast_3_input_bnds_new,
                             input_guess, input_bnds_lo, input_bnds_up,
                             input_bin_bnds,
                             distb_bnds,
                             output_guess, output_bnds_lo, output_bnds_up,
                             fast_state_setpnts, fast_input_setpnts,
                             alpha, alpha_xf, alpha_uf, pred_horzn,
                             pf, pmg, pse, X_int_f2, X_int_f3,
                             i, del_Uc, past_Uc, past_Uz, 
                             alpha_ue, Uc_nb, It_d_Uc, Uc_it_sq, tag,
                             pre_d_Uc, pre_sq_Uc, pre_sq_Uz,
                             pcm, ppn, rxi, rxi_as, yeb)
    
    s_opt = solve_opt_f1(*f_opt)
    
    r_opt = get_results_f1(s_opt[0], pred_horzn)
    
    J = s_opt[1]
    
    return r_opt, J
